import requests
import json


def get_hot_comments(res):
    comments_json = json.loads(res.text)
    hot_comments = comments_json['hotComments']
    with open('hot_comments.txt','w',encoding='utf-8') as file:
        for each in hot_comments:
            file.write(each['user']['nickname']+':\n\n')
            file.write(each['content']+'\n')
            file.write("-------------------------------\n")

def get_comment(url):
    name_id = url.split("=")[1]
    headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
               'referer':'https://music.163.com/song?id=1859652717'}
    
    params="OUqriCHBBKA+ARL6RCJQ9PmNgWKN+U66xQQNQihZQXm0rBxt0dGLwrTRc8+jVRxtI3r4O+uJBZ5iZ7sIzsM12xBmoEtIKAM8YY6GhG39mCp0OlYZzboCiu8mWtpuOrKq8IDwpp7OyJxljQjMZvZdolDIXZ2leMtdmiCJZ2k61hv7GLIgjUaV/nqGLCukp+4egWIU1TatxM7T3BkkK0OP5QlVhqIWLUMSRhUEMFFJzK2VJQmKkrWJKUfaXTUvo5TY3Bh3a6yA9GmFNAvJvds+ijL5mVnBaHTyjs3II+SgRpE="
    encSecKey = "b132c0bfa1b95c8680f7f7632c360c32828d8f5d2acd584b9689b50357e4b9fba6135e886a72898558de21e4433e2763ffefbc11f63212e8e27549639b2666c8c1b4707c05c9f142cc2e2d1173829d103b428cf075f3fdd2469cf2be0dde3a072803bff79ed05388d1d4ad78b07507545c5aa6f470ed6c453ae27af850df77b6"

    data={
        "params":params,
        "encSecKey":encSecKey
        }

    target_url= "https://music.163.com/api/v1/resource/comments/R_SO_4_{}?csrf_token=".format(name_id)
    res = requests.get(target_url,headers=headers,data=data)

    return res
    
def main():
    url=input("请输入链接地址:")
    res = get_comment(url)
    get_hot_comments(res)

    with open("data.txt","w",encoding="utf-8") as file:
        file.write(res.text)

if __name__=="__main__":
    main()
